package com.zz.framework.core.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import com.zz.framework.core.utils.AudioPlayerUtils.Companion.playStatus
import java.io.IOException

/**
 * @version: V1.0
 */
class MediaPlayerUtils private constructor() {
    private var mediaPlayer: MediaPlayer? = null

    // 播放状态枚举，提高代码可读性
    enum class PlayStatus {
        INITIAL, PLAYING, COMPLETED
    }

    private var playStatus = PlayStatus.INITIAL

    companion object {
        @Volatile
        private var instance: MediaPlayerUtils? = null

        fun getInstance(): MediaPlayerUtils {
            return instance ?: synchronized(this) {
                instance ?: MediaPlayerUtils().also { instance = it }
            }
        }
    }

    fun isPlaying(): Boolean = playStatus == PlayStatus.PLAYING

    /**
     * 初始化 MediaPlayer
     */
    private fun initMediaPlayer() {
        releaseMediaPlayer()
        mediaPlayer = MediaPlayer().apply {
            setOnPreparedListener {
                it.start()
                playStatus = PlayStatus.PLAYING
            }
            setOnCompletionListener {
                listener?.invoke()
                playStatus = PlayStatus.COMPLETED
            }
            setOnErrorListener { _, _, _ ->
                // 发生错误时释放资源
                releaseMediaPlayer()
                playStatus = PlayStatus.INITIAL
                true
            }
        }
    }

    var listener: (() -> Unit)? = null
    fun playAudioByUrl(url: String, listener: () -> Unit) {
        try {
            this.listener = listener
            initMediaPlayer()
            mediaPlayer?.apply {
                setDataSource(url)
                setupAudioAttributes()
                isLooping = false
                prepareAsync()
            }
        } catch (e: IOException) {
            e.printStackTrace()
            // 发生错误时释放资源
            releaseMediaPlayer()
            playStatus = PlayStatus.INITIAL
        }
    }

    fun playAudioByAssets(fileName: String, listener: () -> Unit=  {  }) {
        try {
            val context = AppGlobals.getApplication()
            initMediaPlayer() // 确保 MediaPlayer 被正确初始化
            // **加载 Assets 目录下的音频**
            val assetFileDescriptor = context.assets.openFd(fileName)
            this.listener = listener
            initMediaPlayer()
            mediaPlayer?.apply {
                setDataSource(
                    assetFileDescriptor.fileDescriptor,
                    assetFileDescriptor.startOffset,
                    assetFileDescriptor.length
                )
                setupAudioAttributes()
                isLooping = false
                prepareAsync()
            }
        } catch (e: IOException) {
            e.printStackTrace()
            // 发生错误时释放资源
            releaseMediaPlayer()
            playStatus = PlayStatus.INITIAL
        }
    }

    /**
     * 设置音频属性
     */
    private fun MediaPlayer.setupAudioAttributes() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setAudioAttributes(
                AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build()
            )
        } else {
            setAudioStreamType(AudioManager.STREAM_MUSIC)
        }
    }

    /**
     * 停止播放
     */
    fun stop() {
        mediaPlayer?.apply {
            if (isPlaying) {
                stop()
            }
            release()
        }
        listener = null
        mediaPlayer = null
        playStatus = PlayStatus.INITIAL
    }

    /**
     * 释放 MediaPlayer 资源
     */
    private fun releaseMediaPlayer() {
        mediaPlayer?.apply {
            if (isPlaying) {
                stop()
            }
            release()
        }
        mediaPlayer = null
    }

    /**
     * 暂停播放
     */
    fun pause() {
        mediaPlayer?.apply {
            if (isPlaying) {
                pause()
                playStatus = PlayStatus.INITIAL
            }
        }
    }

    /**
     * 继续播放
     */
    fun resume() {
        mediaPlayer?.apply {
            if (!isPlaying && playStatus == PlayStatus.PLAYING) {
                start()
                playStatus = PlayStatus.PLAYING
            }
        }
    }
}